package com.wt.chat.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


/**
 * 非对称加密算法RSA算法组件
 * 非对称算法一般是用来传送对称加密算法的密钥来使用的，相对于DH算法，RSA算法只需要一方构造密钥，不需要
 * 大费周章的构造各自本地的密钥对了。DH算法只能算法非对称算法的底层实现。而RSA算法算法实现起来较为简单
 *
 * @author kongqz
 */
public class RSACoder {

	public static final String RSA_PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIWxWTdOTh+jFcrNDkMd/+R9W81Qzdr5GM9qjU41NNhTfr7fdYJz5EwbzfW+pm8tKRD+EGyiqL4TRbYwgb2QsYsCAwEAAQ==";

	public static final String RSA_PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAhbFZN05OH6MVys0OQx3/5H1bzVDN2vkYz2qNTjU02FN+vt91gnPkTBvN9b6mby0pEP4QbKKovhNFtjCBvZCxiwIDAQABAkBrsH2C1SqMxVsqbp5MZf/X1zp5WdtXxUq82MFV+/nDPePimRuV2uIzmUBJTwhWXPZ8CizTJ1EkTeaSpik5sqmRAiEAw0WjW8GVCp3ROubvLA3WvRhnKJA/FLbQ7ZxSvr2xMF8CIQCvRSW5fPKO2ilivFXJ8UVx2nY3buOGAXbDDotQEb+eVQIgJG5imuTT7KYi+g1Jw/tU+/SIkn3O9wtgkWQf3+w+GZsCIDB/O58FmcA5UXZGkp5cKlEEl+1iu4Ya5Ze3cIjpQFI5AiEAhe8kexTre8jqdWpytBqSHpDjmYf0f9N5wlYhPa0aAIU=";

	//非对称密钥算法
	public static final String KEY_ALGORITHM = "RSA";

	/**
	 * 密钥长度，DH算法的默认密钥长度是1024
	 * 密钥长度必须是64的倍数，在512到65536位之间
	 * 加密数据最长KEY_SIZE / 8 - 11
	 */
	private static final int KEY_SIZE = 512;

	/**
	 * 初始化密钥对
	 *
	 * @return Map 甲方密钥的Map
	 */
	public Map<String, Object> initKey() throws Exception {
		//实例化密钥生成器
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		//初始化密钥生成器
		keyPairGenerator.initialize(KEY_SIZE);
		//生成密钥对
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		//甲方公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		//甲方私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		//将密钥存储在map中
		Map<String, Object> keyMap = new HashMap<String, Object>();
		keyMap.put("p", publicKey);
		keyMap.put("p2", privateKey);
		return keyMap;

	}


	/**
	 * 私钥加密
	 *
	 * @param data 待加密数据
	 * @param key       密钥
	 * @return byte[] 加密数据
	 */
	public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {
		//取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		//生成私钥
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		//数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, privateKey);
		return cipher.doFinal(data);
	}

	/**
	 * 公钥加密
	 *
	 * @param data 待加密数据
	 * @param key       密钥
	 * @return byte[] 加密数据
	 */
	public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {

		//实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		//初始化公钥
		//密钥材料转换
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
		//产生公钥
		PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
		//数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		return cipher.doFinal(data);
	}

	/**
	 * 私钥解密
	 *
	 * @param data 待解密数据
	 * @param key  密钥
	 * @return byte[] 解密数据
	 */
	public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {

		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		//生成私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
		//取得私钥
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
		//数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return cipher.doFinal(data);
	}


	/**
	 * 公钥解密
	 *
	 * @param data 待解密数据
	 * @param key  密钥
	 * @return byte[] 解密数据
	 */
	public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {
		//实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		//初始化公钥
		//密钥材料转换
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
		//产生公钥
		PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
		//数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, pubKey);
		return cipher.doFinal(data);
	}

	public static String decryptByPublicKey(String data, String publicKey) throws Exception {
		return new String(RSACoder.decryptByPublicKey(Base64.decodeBase64(data), Base64.decodeBase64(publicKey)));
	}

	public static String decryptByPrivateKey(String data, String privateKey) throws Exception {
		return new String(RSACoder.decryptByPrivateKey(Base64.decodeBase64(data), Base64.decodeBase64(privateKey)));
	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		//公钥
		byte[] publicKey = Base64.decodeBase64(RSACoder.RSA_PUBLIC_KEY);

		//私钥
		byte[] privateKey = Base64.decodeBase64(RSACoder.RSA_PRIVATE_KEY);

		String str = "RSA密码交换算法,甲方私钥，乙方公钥";
		System.out.println("原文:" + str);
		//甲方进行数据的加密
		byte[] code1 = RSACoder.encryptByPrivateKey(str.getBytes(), privateKey);
		System.out.println("甲方《私钥》加密后的数据：" + Base64.encodeBase64String(code1));
		//乙方进行数据的解密
		byte[] decode1 = RSACoder.decryptByPublicKey(code1, publicKey);
		System.out.println("乙方《公钥》解密后的数据：" + new String(decode1));

		System.out.println("------------------------------------------------");

		//乙方使用公钥对数据进行加密
		byte[] code2 = RSACoder.encryptByPublicKey(str.getBytes(), publicKey);
		System.out.println("乙方《公钥》对数据进行加密后的数据:" + Base64.encodeBase64String(code2));

		//甲方使用私钥对数据进行解密
		byte[] decode2 = RSACoder.decryptByPrivateKey(code2, privateKey);
		System.out.println("甲方《私钥》对数据进行解密：" + new String(decode2));
	}
}